package 力扣_树算法.遍历.层序遍历扩展;

import java.util.ArrayDeque;
import java.util.Deque;

/**117. 填充每个节点的下一个右侧节点指针 II
 * @author zx
 * @create 2022-04-13 12:16
 */
public class 填充每个节点的下一个右侧节点指针II_117 {
    /**
     * @return 层序遍历
     */
    public Node connect(Node root) {
        Deque<Node> queue = new ArrayDeque<>();
        if(root == null){
            return root;
        }
        queue.offer(root);
        while(!queue.isEmpty()){
            int levelCount = queue.size();
            for(int i = 0;i < levelCount;i++){
                Node node = queue.poll();
                if(node.left != null){
                    queue.offer(node.left);
                }
                if(node.right != null){
                    queue.offer(node.right);
                }
                if(i != levelCount - 1){
                    node.next = queue.peek();
                }
            }
        }
        return root;
    }

    /**
     * @return 链表化
     */
    public Node connect2(Node root) {
        if(root == null){
            return root;
        }
        Node cur = root;
        //cur看做是每一层的链表
        while(cur != null){
            Node dummyHead = new Node(101);
            Node prev = dummyHead;
            //遍历当前层的链表
            while(cur != null){
                //如果当前节点的左子节点不为空,就让pre节点的next指向他,将其串起来
                if(cur.left != null){
                    prev.next = cur.left;
                    prev = prev.next;
                }
                if(cur.right != null){
                    prev.next = cur.right;
                    prev = prev.next;
                }
                //继续访问这一行的下一个节点
                cur = cur.next;
            }
            //访问下一层
            cur = dummyHead.next;
        }
        return root;
    }

    private class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    }
}
